package com.wxy.favorites.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.wxy.favorites.constant.PublicConstants;
import com.wxy.favorites.core.BizException;
import com.wxy.favorites.core.NoRollbackException;
import com.wxy.favorites.core.PageInfo;
import com.wxy.favorites.dao.ClockRepository;
import com.wxy.favorites.dto.ClockNoticeDto;
import com.wxy.favorites.entity.Clock;
import com.wxy.favorites.security.ContextUtils;
import com.wxy.favorites.util.AssertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author wangxiaoyuan
 * @Date 2020/4/24 11:50
 * @Description
 **/
@Slf4j
@Service
@Transactional(noRollbackFor = NoRollbackException.class)
public class ClockService {

    @Autowired
    private ClockRepository clockRepository;

    public Clock save(Clock clock) {
        try {
            clock.setTime(DateUtil.format(DateUtil.parse(clock.getTime(), PublicConstants.FORMAT_MIN_PATTERN), PublicConstants.FORMAT_MIN_PATTERN));
        } catch (Exception e) {
            throw new BizException("格式不合法");
        }
        AssertUtils.isTrue(!Objects.equals(clock.getType(), 2) || StrUtil.isNotBlank(clock.getCycle()), "请选择周期");
        Integer userId = ContextUtils.getCurrentUser().getId();
        clock.setUserId(userId);
        clock.setStatus(1);
        return clockRepository.save(clock);
    }

    public void deleteById(Integer id) {
        clockRepository.deleteById(id);
    }

    public Integer enable(Integer id) {
        Clock clock = clockRepository.findById(id).orElseThrow(() -> new BizException("闹钟不存在"));
        clock.setStatus(clock.getStatus() == 1 ? 0 : 1);
        clockRepository.save(clock);
        return clock.getStatus();
    }

    public PageInfo<Clock> findPageByUserId(Integer userId, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<Clock> page = clockRepository.findAllByUserId(userId, pageable);
        return new PageInfo<>(page.getContent(), page.getTotalPages(), page.getTotalElements());
    }

    public List<ClockNoticeDto> findClockListByNow() {
        Date now = new Date();
        String time = DateUtil.format(now, PublicConstants.FORMAT_MIN_PATTERN);
        // 每天
        List<Clock> list = clockRepository.findAllByTimeAndStatusAndType(time, 1, 0);
        // 周一到周五
        if (!DateUtil.isWeekend(now)) {
            list.addAll(clockRepository.findAllByTimeAndStatusAndType(time, 1, 1));
        }
        // 自定义
        int week = DateUtil.weekOfMonth(now);
        list.addAll(clockRepository.findAllByTimeAndStatusAndTypeAndCycleLike(time, 1, 2, "%" + week + "%"));
        // 去重
        return list.stream().collect(Collectors.groupingBy(Clock::getUserId)).entrySet().stream().map(entry -> new ClockNoticeDto().setUserId(entry.getKey()).setContent(entry.getValue().stream().map(Clock::getContent).collect(Collectors.joining("<br>")))).toList();
    }
}

